from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
import pymongo
from aip import AipOcr
import re
import time
from PIL import Image
from io import BytesIO
import threading

APP_ID = '24217351'
API_KEY = '7vRbBsMqcMPyFqry1nxwTdrH'
SECRET_KEY = 'LqoitsxibGBdy149lHlIOzBueTEHE8Nv'
client = AipOcr(APP_ID, API_KEY, SECRET_KEY)


def get_num():
    pic = open('test.png', 'rb').read()
    options = {"language_type": "CHN_ENG"}
    res = client.basicGeneral(pic, options)
    try:
        return res.get('words_result')[0].get('words')
    except:
        print(res)
        return 1


def task():
    conn = pymongo.MongoClient('mongodb://47.93.220.108:27017/')['movie']['unplay']
    conn.delete_many({})

    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    driver = webdriver.Chrome(executable_path='/Users/aaa/py/chromedriver',options=options)
    driver.get('https://piaofang.maoyan.com/store')
    time.sleep(2)
    item = driver.find_element_by_css_selector('#movie-list')
    all_movies = item.find_elements_by_css_selector('article')
    for i in all_movies:
        name = i.find_element_by_css_selector('div').text
        online_time = i.text.split('\n')[2]
        desire_pic = i.find_element_by_css_selector('em > span').screenshot_as_png
        pic = Image.open(BytesIO(desire_pic)).save('./test.png')
        desire = get_num()
        img_content = i.get_attribute('data-com')
        img_url = re.findall("'(.*)'", img_content)
        cur = driver.current_window_handle
        driver.execute_script(f'window.open("{"https://piaofang.maoyan.com" + img_url[0]}");')
        driver.switch_to.window(driver.window_handles[-1])
        time.sleep(2)
        img = driver.find_element_by_css_selector('.need-handle-pic').get_attribute('src')
        driver.close()
        driver.switch_to.window(cur)
        conn.insert_one({'movie_name': name, 'movie_time': online_time, 'movie_desire': desire, 'movie_img': img})


curTime = time.strftime("%Y-%M-%D", time.localtime())  # 记录当前时间
execF = False
ncount = 0


def timerTask():
    global execF
    global curTime
    global ncount
    if execF is False:
        task()  # 判断任务是否执行过，没有执行就执行
        execF = True
    else:  # 任务执行过，判断时间是否新的一天。如果是就执行任务
        desTime = time.strftime("%Y-%M-%D", time.localtime())
        if desTime > curTime:
            execF = False  # 任务执行执行置值为
            curTime = desTime
    ncount = ncount + 1
    timer = threading.Timer(3600, timerTask)
    timer.start()
    print("定时器执行%d次" % ncount)


if __name__ == '__main__':
    timer = threading.Timer(5, timerTask)
    timer.start()
